﻿using System;
using System.Runtime.InteropServices;
using RayDen.Library.Core.Primitives;

namespace RayDen.Library.Core
{
    [StructLayout(LayoutKind.Explicit)]
    public struct Int32Single : ISerializableValue
    {
        /// <summary>
        /// Integer value.
        /// </summary>
        [FieldOffset(0)]
        internal Int32 i;

        /// <summary>
        /// Unsigned integer value.
        /// </summary>
        [FieldOffset(0)]
        internal UInt32 u;

        /// <summary>
        /// Floating point value.
        /// </summary>
        [FieldOffset(0)]
        internal Single f;

        public static implicit operator float(Int32Single n)
        {
            return n.f;
        }

        public static implicit operator UInt32(Int32Single n)
        {
            return n.u;
        }

        public static Int32Single Create(Int32 i)
        {
            return new Int32Single() { i = i };
        }
        public static Int32Single Create(Single i)
        {
            return new Int32Single() { f = i };
        }

        public static Int32Single Create(byte[] data, int startIndex = 0)
        {
            return new Int32Single()
                {
                    f = BitConverter.ToSingle(data, startIndex)
                };
        }

        public byte[] GetBytes()
        {
            return BitConverter.GetBytes(this.u);
        }


        public byte[] Serialize()
        {
            return BitConverter.GetBytes(this.f);
        }

        public void Deserialize(byte[] data, int offset = 0)
        {
            this.f = BitConverter.ToSingle(data, offset);
        }
    }
}